package com.hwl.cms.controller.admin;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hwl.cms.pojo.Ad;
import com.hwl.cms.pojo.vo.AdVo;
import com.hwl.cms.service.AdService;
import com.hwl.commonutils.result.RespBean;
import com.hwl.commonutils.utils.AssertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 广告推荐 前端控制器
 * </p>
 *
 * @author long
 * @since 2021-10-06
 */
@Api(tags = "广告管理")
@RestController
@RequestMapping("/admin/cms/ad")
public class AdController {

    @Resource
    private AdService adService;

    @ApiOperation("根据ID删除广告")
    @DeleteMapping("remove/{id}")
    public RespBean removeById(@PathVariable String id) {
        //删除广告图片
        adService.removeAdImage(id);

        if (adService.removeById(id)) {
            return RespBean.ok().message("删除广告成功！");
        }
        return RespBean.error().message("删除广告失败！");
    }

    @ApiOperation("获取广告分页列表")
    @GetMapping("list/{page}/{limit}")
    public RespBean listPage(@PathVariable Long page, @PathVariable Long limit) {
        IPage<AdVo> iPage = adService.selectPage(page, limit);
        return RespBean.ok().data(iPage);
    }

    @ApiOperation("新增广告")
    @PostMapping("save")
    public RespBean save(@RequestBody Ad ad) {
        AssertUtil.isTrue(adService.getAdByTitle(ad.getTitle()) != null, "广告标题不得重复！");
        if (adService.save(ad)) {
            return RespBean.ok().message("新增广告成功！");
        }
        return RespBean.error().message("新增广告失败！");
    }

    @ApiOperation("更新广告内容")
    @PutMapping("update")
    public RespBean updateById(@RequestBody Ad ad) {
        Ad adByTitle = adService.getAdByTitle(ad.getTitle());
        AssertUtil.isTrue(adByTitle != null && !adByTitle.getId().equals(ad.getId()), "广告标题不得重复!");

        if (adService.updateById(ad)) {
            return RespBean.ok().message("更新广告成功！");
        }
        return RespBean.error().message("更新广告失败！");
    }

    @ApiOperation("根据id获取广告信息")
    @GetMapping("get/{id}")
    public RespBean getById(@PathVariable String id) {
        return RespBean.ok().data(adService.getById(id));
    }


}

